package br.edu.senai.converter;

import br.edu.senai.controller.ClienteDAO;
import br.edu.senai.model.Cliente;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("clienteConverter")
public class ClienteConverter implements Converter {

    private final ClienteDAO cdao = new ClienteDAO();

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        try {
            return cdao.find(Long.parseLong(value));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return value != null ? (value.getClass().equals(Cliente.class) ? ((Cliente) value).getId() + "" : null) : null;
    }
}
